const app = getApp();
import api from "../../../common/api"
import * as user from '../../../models/user'
import locationBehavior from '../../../behaviors/location';
import {
  dialog
} from '../../../component/userStatusDialog/control'
import * as filter from '../../../models/filterConfigs'

Page({
  behaviors: [locationBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    tabList: [{
      id: 'OWERN',
      label: '全网业主房',
      add: '',
    }, {
      id: 'SUBSCRIBE',
      label: '我的订阅',
      add: '',
    }],
    defaultTabSelect: '',
    tabSelect: '',
    districtOptions: '',
    cityName: '',
    cityCode: '',
    contentNum: '', //查询订阅的数量
    importNum: '', //导入成功的数量
    isFirstTime: '', //判断是否是第一次导入房源情报
    salesType: 'SUBSCRIBE'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 登录授权验证
    app.mobileLogin(null, "业主房源情报", null)
      .then(() => {
        this.getCurrentCity()
          .then(() => {
            this.getBizcircles(this.data.cityCode)
              .then(() => {
                this.initData(options)
              })
          })
      })
      .catch(() => {
        app.globalData.afterMobileAuthorCallBack = () => {
          wx.redirectTo({
            url: "/pages/home/propertyOwner/propertyOwner"
          });
        };
      });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (optionss) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().globalData.loginPromise.then(() => {
      this.deleteUnReadCount() //页面一进入到业主房源就开始去清楚未读消息
      this.getSubscribeResblockCount()
      this.userBehavior_find()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //切换tab
  onTabChange(e) {
    const {
      tabSelect
    } = this.data
    let target = e.detail
    if (tabSelect === target) return

    this.setData({
      tabSelect: target,
      filterRange: '',
      filterType: '',
    })
  },
  // 默认显示组件
  initData(options) {
    this.setData({
      defaultTabSelect: options.tab || 'OWERN',
      tabSelect: options.tab || 'OWERN'
    })
  },
  // 准备商圈
  getBizcircles(cityCode = '') {
    return new Promise((resolve, reject) => {
      api.getBizcircles({
        cityCode
      }, (res) => {
        if (res && res.data && res.data.content && res.data.content.length) {
          this.setData({
            districtOptions: filter.formatDistrictOptions(res.data.content)
          })
          resolve()
        } else {
          reject()
        }
      })
    })
  },
  // 获取当前城市
  getCurrentCity() {
    return new Promise((resolve, reject) => {
      this.getCityInfoNew().then(({
        city,
        cityCode
      }) => {
        this.setData({
          cityName: city,
          cityCode: cityCode,
        });

        resolve()
      })
    })
  },
  // 点击订阅业主房源
  onClickSubscribe(e) {
    user.getVip(true)
      .then(res => {
        if (res == '0') { //会员
          let that = this
          that.checkOfficialAccount()
            .then(() => {
              if (that.data.contentNum && that.data.contentNum !== 0 && that.data.isFirstTime === 0) { //这里需要判断是否关注过房源情报 并且是否是第一次展示
                wx.showModal({
                  title: '温馨提示',
                  content: `您房源情报已订阅过${that.data.contentNum}个小区 可一键批量订阅已订阅小区`,
                  cancelText: '重新订阅',
                  confirmText: '导入订阅',
                  confirmColor: '#F75352',
                  success: (res) => {
                    if (res.confirm) {
                      // 用户点击导入订购
                      that.userBehavior_add('2')
                      that.importIntelligenceSubResb()
                        .then(() => {
                          wx.showModal({
                            title: '温馨提示',
                            content: that.data.importNum,
                            cancelText: '关闭',
                            confirmText: '继续订阅',
                            confirmColor: '#F75352',
                            success: (res) => {
                              if (res.confirm) {
                                wx.navigateTo({
                                  url: '/pages/home/propertyOwner/com/select/select'
                                })
                              } else if (res.cancel) {
                                // 点击了关闭
                                wx.redirectTo({
                                  url: `/pages/home/propertyOwner/propertyOwner?tab=${that.data.salesType}`,
                                })
                              }
                            }
                          })
                        })

                    } else if (res.cancel) {
                      // 点击重新订阅
                      that.userBehavior_add('1')
                      wx.navigateTo({
                        url: '/pages/home/propertyOwner/com/select/select'
                      })

                    }
                  }
                })
              } else {
                // 未订阅房源情报
                wx.navigateTo({
                  url: '/pages/home/propertyOwner/com/select/select'
                })
              }
            })
            .catch(() => {
              dialog({
                dialog: 'allFunctions',
                confirm: () => {
                  let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
                  wx.navigateTo({
                    url: `/pages/webView/webView?webViewUrl=${url}`
                  })
                },
                cancel: () => {
                  wx.showModal({
                    title: '',
                    content: '距离开启业主情报功能只有一步，你是否确定放弃',
                    confirmText: '去完成',
                    cancelText: '残忍放弃',
                    confirmColor: '#F75352',
                    success(res) {
                      if (res.confirm) {
                        let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
                        wx.navigateTo({
                          url: `/pages/webView/webView?webViewUrl=${url}`
                        })
                      }
                    }
                  })
                }
              })
            })
        } else {
          dialog({
            dialog: res == '3' ? 'superVip' : 'due',
            confirm: () => {
              wx.navigateTo({
                url: '/pages/mine/memberCentre/memberCentre'
              })
            }
          })
        }
      })
  },
  // 判断是否关注公众号
  checkOfficialAccount() {
    return new Promise((resolve, reject) => {
      user.getOfficialAccount(true)
        .then(res => {
          if (res === '1') {
            resolve()
          } else {
            reject()
          }
        })
        .catch(() => {
          wx.showToast({
            icon: 'none',
            title: '网络错误，请稍后再试~',
          })
        })
    })
  },

  // 查询房源情报订阅小区数量
  getSubscribeResblockCount() {
    return new Promise((resolve, reject) => {
      api.getSubscribeResblockCount({}, (res) => {
        if (res && res.data && res.data.content) {
          this.setData({
            contentNum: res.data.content
          })
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  //导入房源情报订阅小区
  importIntelligenceSubResb() {
    return new Promise((resolve, reject) => {
      api.importIntelligenceSubResb({}, (res) => {
        if (res && res.data && res.data.isSuccess) {
          this.setData({
            importNum: res.data.content
          })
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  // 用户行为记录 1是重新订阅；  2是导入已订阅
  userBehavior_add(tmp) {
    return new Promise((resolve, reject) => {
      api.userBehavior_add({
        userBehavior: tmp
      }, (res) => {
        if (res && res.data && res.data.isSuccess) {
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  // 用户行为查询
  userBehavior_find() {
    return new Promise((resolve, reject) => {
      api.userBehavior_find({}, (res) => {
        if (res && res.data && res.data.isSuccess) {
          this.setData({
            isFirstTime: res.data.content
          })
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  // 清楚业主情报未读
  deleteUnReadCount() {
    return new Promise((resolve, reject) => {
      api.deleteUnReadCount({}, (res) => {
        if (res && res.data && res.data.isSuccess) {
          resolve()
        } else {
          reject()
        }
      })
    })
  },
})